import {createApp} from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router/index'
import './styles/index.scss'
import {createPinia} from "pinia";
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'virtual:svg-icons-register'
import 'amfe-flexible'
import { useStore } from "@/store";


const pinia = createPinia()
const app = createApp(App)
// 先安装 Pinia
app.use(pinia)

// 添加应用初始化逻辑
async function initApp() {
  const store = useStore()

  // 从sessionStorage获取用户信息
  const tokenInfo = sessionStorage.getItem('token');
  if (tokenInfo) {
    try {
      const { username, token } = JSON.parse(tokenInfo);
      // 设置用户信息到store
      store.user.setUserInfo({  username, token });
       // 如果学期信息为空，预加载数据
    if (!store.home.semesterInfo || store.home.semesterInfo.length === 0) {
      await store.home.getSemesterData();
    }
     if (!store.record.records || store.record.records.length === 0) {
      await store.record.fetchRecords();
     }
    } catch (error) {
      // 如果解析失败，清除无效的token
      sessionStorage.removeItem('token');
    }
  }

  
  // // 获取当前学期信息并设置可操作学期
  // store.home.getSemesterData().then(() => {
  //    // 获取学期信息
  //   const semesterInfo = store.home.getSemesterInfo
  //   if (semesterInfo && semesterInfo.length > 0) {
  //     // 实际项目中应该根据业务逻辑判断哪个学期是当前可操作的
  //     const currentSemesterId = semesterInfo[semesterInfo.length - 1].SEMESTER_ID
  //     // 设置当前可操作学期
  //     store.settings.setCurrentOperableSemester(currentSemesterId)
  //     // 也可以设置可操作学期列表
  //     store.settings.setOperableSemesters([currentSemesterId])
  //   }
  // })
}
// 在挂载应用前初始化
initApp();


for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
app.use(ElementPlus)
app.use(router)
app.mount('#app')

